package com.b1.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.FileUtils;
import com.b1.common.ErrorCode;
import com.b1.constant.CommonConstant;
import com.b1.exception.BusinessException;
import com.b1.exception.ThrowUtils;
import com.b1.mapper.ChildernSleepRecordMapper;
import com.b1.pojo.dto.childernSleepRecord.ChildernSleepExport;
import com.b1.pojo.dto.childernSleepRecord.ChildernSleepQueryRequest;
import com.b1.pojo.enity.ChildernSleepRecord;
import com.b1.pojo.enums.*;
import com.b1.service.ChildernSleepRecordService;
import com.b1.utils.AliOssUtil;
import com.b1.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author ThinkBook
 * @description 针对表【childern_sleep_record(这是用来管理每个班级儿童的午睡情况的记录表)】的数据库操作Service实现
 * @createDate 2024-10-09 15:44:24
 */
@Service
public class ChildernSleepRecordServiceImpl extends ServiceImpl<ChildernSleepRecordMapper, ChildernSleepRecord>
        implements ChildernSleepRecordService {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Override
    public void validChildernSleepRecord(ChildernSleepRecord childernSleepRecord, boolean add) {
        if (childernSleepRecord == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String className = childernSleepRecord.getClassName();
        String teacherName = childernSleepRecord.getTeacherName();
        String kindName = childernSleepRecord.getKindName();
        Integer isQuite = childernSleepRecord.getIsQuite();
        Integer closthSkill = childernSleepRecord.getClosthSkill();
        Integer sleepEnvironment = childernSleepRecord.getSleepEnvironment();
        Integer sleepPosition = childernSleepRecord.getSleepPosition();
        Integer closthSuit = childernSleepRecord.getClosthSuit();
        Integer isWindows = childernSleepRecord.getIsWindows();
        Integer isSweat = childernSleepRecord.getIsSweat();
        Integer visitationStatus = childernSleepRecord.getVisitationStatus();
        Integer isWake = childernSleepRecord.getIsWake();
        Integer isError = childernSleepRecord.getIsError();
        String errorDesc = childernSleepRecord.getErrorDesc();
        String notes = childernSleepRecord.getNotes();


        // 创建时，参数不能为空
        if (add) {
            //
            ThrowUtils.throwIf(StringUtils.isAnyBlank(className, teacherName, kindName), ErrorCode.PARAMS_ERROR, "创建时这些参数不能为空");

        }
        // 有参数则校验
        if (StringUtils.isNotBlank(className) && className.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "班级名称过长，不能超过20字");
        }
        if (StringUtils.isNotBlank(teacherName) && teacherName.length() > 10) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "教师名称过长");
        }
        if (StringUtils.isNotBlank(kindName) && kindName.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "幼儿名称过长");
        }
        if (StringUtils.isNotBlank(errorDesc) && errorDesc.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "异常情况说明过长");
        }
        if (StringUtils.isNotBlank(notes) && notes.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "备注过长");
        }
        //状态字段校验
        ThrowUtils.throwIf(isQuite != null && (isQuite < 0 || isQuite > 1), ErrorCode.PARAMS_ERROR, "是否盖被子参数错误");
        ThrowUtils.throwIf(closthSkill != null && (closthSkill < 0 || closthSkill > 2), ErrorCode.PARAMS_ERROR, "穿衣技能参数错误");
        ThrowUtils.throwIf(sleepEnvironment != null && (sleepEnvironment < 0 || sleepEnvironment > 1), ErrorCode.PARAMS_ERROR, "午睡环境参数错误");
        ThrowUtils.throwIf(sleepPosition != null && (sleepPosition < 0 || sleepPosition > 1), ErrorCode.PARAMS_ERROR, "睡眠姿势参数错误");
        ThrowUtils.throwIf(isSweat != null && (isSweat < 0 || isSweat > 1), ErrorCode.PARAMS_ERROR, "是否出汗参数错误");
        ThrowUtils.throwIf(isWake != null && (isWake < 0 || isWake > 1), ErrorCode.PARAMS_ERROR, "是否醒来参数错误");
        ThrowUtils.throwIf(isError != null && (isError < 0 || isError > 1), ErrorCode.PARAMS_ERROR, "是否异常参数错误");
        ThrowUtils.throwIf(closthSuit != null && (closthSuit < 0 || closthSuit > 1), ErrorCode.PARAMS_ERROR, "穿衣是否适宜参数错误");
        ThrowUtils.throwIf(visitationStatus != null && (visitationStatus < 0 || visitationStatus > 5), ErrorCode.PARAMS_ERROR, "教师巡视情况参数错误");
        ThrowUtils.throwIf(isWindows != null && (isWindows < 0 || isWindows > 1), ErrorCode.PARAMS_ERROR, "是否开窗参数错误");
    }

    @Override
    public QueryWrapper<ChildernSleepRecord> getQueryWrapper(ChildernSleepQueryRequest childernSleepQueryRequest) {
        QueryWrapper<ChildernSleepRecord> queryWrapper = new QueryWrapper<>();
        if (childernSleepQueryRequest == null) {
            return queryWrapper;
        }
        Integer id = childernSleepQueryRequest.getId();
        String className = childernSleepQueryRequest.getClassName();
        String teacherName = childernSleepQueryRequest.getTeacherName();
        String kindName = childernSleepQueryRequest.getKindName();
        Integer isWindows = childernSleepQueryRequest.getIsWindows();
        Integer isQuite = childernSleepQueryRequest.getIsQuite();
        Integer closthSkill = childernSleepQueryRequest.getClosthSkill();
        Integer sleepEnvironment = childernSleepQueryRequest.getSleepEnvironment();
        Integer sleepPosition = childernSleepQueryRequest.getSleepPosition();
        Integer closthSuit = childernSleepQueryRequest.getClosthSuit();
        Integer isFace = childernSleepQueryRequest.getIsFace();
        Integer isSweat = childernSleepQueryRequest.getIsSweat();
        Integer visitationStatus = childernSleepQueryRequest.getVisitationStatus();
        Date cheakTimeEnd = childernSleepQueryRequest.getCheakTimeEnd();
        Date cheakTimeStart = childernSleepQueryRequest.getCheakTimeStart();
        Double sleepRate = childernSleepQueryRequest.getSleepRate();
        Integer isWake = childernSleepQueryRequest.getIsWake();
        Integer isError = childernSleepQueryRequest.getIsError();
        String errorDesc = childernSleepQueryRequest.getErrorDesc();
        String notes = childernSleepQueryRequest.getNotes();
        String sortField = childernSleepQueryRequest.getSortField();
        String sortOrder = childernSleepQueryRequest.getSortOrder();
        // 拼接查询条件
        //模糊查询
        queryWrapper.like(StringUtils.isNotBlank(errorDesc), "errorDesc", errorDesc);
        queryWrapper.like(StringUtils.isNotBlank(notes), "notes", notes);
        queryWrapper.like(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.like(StringUtils.isNotBlank(kindName), "kindName", kindName);
        //精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq(ObjectUtils.isNotEmpty(teacherName), "teacherName", teacherName);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isQuite), "isQuite", isQuite);
        queryWrapper.eq(ObjectUtils.isNotEmpty(closthSkill), "closthSkill", closthSkill);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sleepEnvironment), "sleepEnvironment", sleepEnvironment);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sleepPosition), "sleepPosition", sleepPosition);
        queryWrapper.eq(ObjectUtils.isNotEmpty(closthSuit), "closthSuit", closthSuit);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isFace), "isFace", isFace);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isSweat), "isSweat", isSweat);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isWindows), "isWindows", isWindows);
        queryWrapper.eq(ObjectUtils.isNotEmpty(visitationStatus), "visitationStatus", visitationStatus);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sleepRate), "sleepRate", sleepRate);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isWake), "isWake", isWake);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isError), "isError", isError);


        //时间范围查询
        if (ObjectUtils.isEmpty(cheakTimeStart)){
            //如果开始时间为空，则默认2000年1月1日
            cheakTimeStart=Date.from(LocalDateTime.of(2000,1,1,0,0,0).atZone(ZoneId.systemDefault()).toInstant());

        }
        if (ObjectUtils.isEmpty(cheakTimeEnd)){
            //如果结束时间为空，则默认当前时间
            cheakTimeEnd=Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        }
        queryWrapper.between("cheakTime", cheakTimeStart, cheakTimeEnd);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 导出数据
     *
     * @param ids
     * @return
     */
    @Override
    public String export(Long[] ids) throws IOException {
        List<ChildernSleepRecord> childernSleepRecords = listByIds(Arrays.asList(ids));
        List<ChildernSleepExport> childernSleepExports = new ArrayList<>();
        for (ChildernSleepRecord record : childernSleepRecords) {
            ChildernSleepExport export = new ChildernSleepExport();

            //将数字状态转换为对应的文字
            export.setIsQuite(Objects.requireNonNull(StatusEnum.getEnumByValue(record.getIsQuite())).getText());
            export.setClosthSkill(Objects.requireNonNull(ClosthSkillEnum.getEnumByValue(record.getClosthSkill())).getText());
            export.setSleepEnvironment(Objects.requireNonNull(SleepEnviromentEnum.getEnumByValue(record.getSleepEnvironment())).getText());
            export.setSleepPosition(Objects.requireNonNull(SleepPositionEnum.getEnumByValue(record.getSleepPosition())).getText());
            export.setClosthSuit(Objects.requireNonNull(ClosthSuitEnum.getEnumByValue(record.getClosthSuit())).getText());
            export.setIsWindows(Objects.requireNonNull(StatusEnum.getEnumByValue(record.getIsQuite())).getText());
            export.setIsSweat(Objects.requireNonNull(YesOrNoEnum.getEnumByValue(record.getIsSweat())).getText());
            export.setIsFace(Objects.requireNonNull(YesOrNoEnum.getEnumByValue(record.getIsFace())).getText());
            export.setVisitationStatus(Objects.requireNonNull(VistitionStatusEnum.getEnumByValue(record.getVisitationStatus())).getText());
            export.setIsWake(Objects.requireNonNull(YesOrNoEnum.getEnumByValue(record.getIsWake())).getText());
            export.setIsError(Objects.requireNonNull(YesOrNoEnum.getEnumByValue(record.getIsError())).getText());
            export.setId(record.getId());
            export.setClassName(record.getClassName());
            export.setNotes(record.getNotes());
            export.setSleepRate(record.getSleepRate());
            export.setErrorDesc(record.getErrorDesc());
            export.setTeacherName(record.getTeacherName());
            childernSleepExports.add(export);
        }
        String upload;
        //创建一个临时文件写入
        File file = new File("childernSleepRecord.xlsx");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            //将数据写入临时文件
            EasyExcel.write(fos, ChildernSleepExport.class).sheet("幼儿园午睡情况记录表").doWrite(childernSleepExports);
        }catch (Exception exception){
            throw new RuntimeException("导出失败");
        }
        //将临时文件上传到阿里云oss
        String fileName="幼儿园午睡情况记录表"+System.currentTimeMillis()+".xlsx";
        //将 file转为byte

            byte[] bytes = FileUtils.readFileToByteArray(file);
            upload = aliOssUtil.upload(bytes, fileName);

        return upload;
    }

    @Transactional
    @Override
    public Boolean updateBatch(List<ChildernSleepRecord> childernSleepRecords) {
        return this.updateBatchById(childernSleepRecords);
    }

}




